<template>
  <el-card shadow="never" class="aui-card--fill">
    <el-container>
      <el-form
        size="mini"
        :inline="true"
        :model="queryForm"
        @keyup.enter.native="query()"
      >
        <el-form-item label="">
          <el-input
            v-model="queryForm.quotaName"
            placeholder="输入指标名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="行业">
          <el-select v-model="queryForm.name" @change="hangyeChange" placeholder="请选择行业名称">
            <el-option
              v-for="item in nameList"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
          <!-- 行业 -->
          <!-- <ren-select v-model="queryForm.gender" dict-type="gender" :placeholder="$t('user.gender')"></ren-select> -->
        </el-form-item>
        <el-form-item label="更新频率">
          <ren-select
            v-model="queryForm.updateFrequency"
            dict-type="quotaUpdateFrequency"
            placeholder="更新频率"
          ></ren-select>
        </el-form-item>
        <el-form-item label="数据来源">
          <ren-select
            v-model="queryForm.dataSourceType"
            dict-type="quotaSourceType"
            placeholder="数据来源"
          />
        </el-form-item>
        <el-form-item label="是否首页展示">
          <ren-select
            v-model="queryForm.isDisplay"
            dict-type="quotaIsDisplayType"
            placeholder="首页展示"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button @click="clear">重置</el-button>
          <!-- <el-button type="primary" @click="add">新增指标</el-button> -->
        </el-form-item>
      </el-form>
    </el-container>
    <el-container style="height: 810px">
      <el-aside width="180px">
        <el-tree
          class="quota-tree"
          ref="tree"
          :data="moduleTree"
          @check-change="handleCheckChange"
          @current-change="handleCurrentChange"
          node-key="id"
          :props="treeProps"
        >
        <span slot-scope="{ node }" :title="node.label">
			<span @click="handleClickLocationFun(node)">
			{{ node.label }}
			</span> 
			</span>

        </el-tree>
      </el-aside>
      <el-main>
        <div class="table-top">
          <div class="left">
            <div class="top-line"></div>
            指标管理列表
          </div>
          <div class="right">
            <div class="table-top-btn" @click="add">新增指标</div>
          </div>
        </div>
        <el-table
          v-loading="dataListLoading"
          :data="dataList"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column
            prop="industryName"
            label="行业名称"
          ></el-table-column>
          <el-table-column
            prop="industryType"
            label="一级模块"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="secondModuleName"
            label="二级模块"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="quotaName"
            label="指标名称"
            width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column prop="quotaSort" label="指标排序"></el-table-column>
<!--          <el-table-column-->
<!--            prop="districtAnalysisHotmap"-->
<!--            label="区市分布(热力图)"-->
<!--          >-->
<!--            <template slot-scope="{ row }">-->
<!--              <span>{{ row.districtAnalysisHotmap == 1 ? "是" : "否" }}</span>-->
<!--            </template></el-table-column-->
<!--          >-->
          <el-table-column
            prop="districtAnalysisPointMap"
            label="区市分布(点位图)"
          >
            <template slot-scope="{ row }">
              <span>{{ row.districtAnalysisPointMap == 1 ? "是" : "否" }}</span>
            </template></el-table-column
          >
          <el-table-column prop="timeTrend" label="趋势变化">
            <template slot-scope="{ row }">
              <span>{{ row.timeTrend == 1 ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="quotaLimit" label="展示条数">
          </el-table-column> -->
          <el-table-column prop="categoryAnalysis" label="结构分析">
            <template slot-scope="{ row }">
              <span>{{ row.categoryAnalysis == 1 ? "是" : "否" }}</span>
            </template></el-table-column
          >
          <el-table-column prop="detailList" label="明细清单">
            <template slot-scope="{ row }">
              <span>{{ row.detailList == 1 ? "是" : "否" }}</span>
            </template></el-table-column
          >
          <el-table-column prop="quotaType" label="正负类型">
            <template slot-scope="{ row }">
              <span>{{ row.quotaType == 1 ? "负" : "正" }}</span>
            </template></el-table-column
          >
          <el-table-column prop="dataUpdateFrequency" label="更新频率">
            <template slot-scope="{ row }">
              <span>{{
                $getDictLabel("quotaUpdateFrequency", row.dataUpdateFrequency)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="dataSourceType"
            label="数据来源"
          ></el-table-column>
          <el-table-column prop="isDisplay" label="驾驶舱首页展示">
            <template slot-scope="{ row }">
              <span>{{ row.isDisplay == 1 ? "是" : "否" }}</span>
            </template></el-table-column
          >
          <el-table-column
            prop="yoyMom"
            label="同比/环比展示"
            width="88"
          >
            <template slot-scope="{ row }">
              <span>{{ row.yoyMom == 1 ? "同比" : row.yoyMom == 2 ? "环比" : "" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="mobileLayout"
            label="移动端布局"
            width="72"
          ></el-table-column>
          <el-table-column prop="delFlag" label="状态">
            <template slot-scope="{ row }">
              <span>{{ row.quotaType == 1 ? "禁用" : "正常" }}</span>
            </template>
          </el-table-column>

          <!-- categoryAnalysis: "否"
dataSourceType: ""
dataUpdateFrequency: "月度"
delFlag: "正常"
detailList: "否"
districtAnalysisHotmap: "否"
districtAnalysisPointMap: "否"
id: 220011
industryName: "广告牌匾"
industryType: "安全信息"
isDisplay: "是"
quotaName: "招牌破损数"
quotaSort: null
quotaType: "正"
secondModuleName: "安全信息"
timeTrend: "否" -->
          <el-table-column
            :label="$t('handle')"
            fixed="right"
            header-align="center"
            align="center"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="addOrUpdateHandle(scope.row)"
                >{{ $t("update") }}</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="deleteHandle(scope.row.id)"
                >{{ $t("delete") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          :total="+page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="pageSizeChangeHandle"
          @current-change="pageCurrentChangeHandle"
        >
        </el-pagination>
      </el-main>
      <add-or-update
        v-if="addOrUpdateVisible"
        ref="addOrUpdate"
        :name-list="nameList"
        :module-tree="subModuleTree"
        @refreshDataList="query"
      ></add-or-update>
    </el-container>
  </el-card>
</template>

<script>
import AddOrUpdate from './quota-add-or-update'
import { getDictDataList } from '@/utils'
const URL_GET_ALL_MODULE = '/cgjybzIndustry/getModuleInfo'
const URL_DELETE = '/cgjybzIndustry/delRelation'

function createForm (arg) {
  return {
    dataSourceType: '',
    isDisplay: '',
    name: '',
    quotaName: '',
    updateFrequency: ''
  }
}

export default {
  components: {
    AddOrUpdate
  },
  name: 'QuotaIndex',
  data () {
    return {
      page: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      dataList: [],
      addOrUpdateVisible: false,
      dataListLoading: false,
      queryForm: createForm(),
      moduleTree: [],
      selectedModule: [],
      treeProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    subModuleTree () {
      return this.moduleTree.reduce((ret, cur) => {
        ret = ret.concat(cur.children)
        return ret
      }, [])
    },
    nameList () {
      return this.moduleTree.reduce((ret, cur) => {
        ret = ret.concat(cur.children.map((c) => c.name))
        return ret
      }, [])
    }
  },
  mounted () {
    this.initData()
    this.query()
  },
  activated () {
    this.query()
  },
  methods: {
    add () {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init()
      })
    },
    deleteHandle (id) {
      this.$confirm(
        this.$t('prompt.info', { handle: this.$t('delete') }),
        this.$t('prompt.title'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.$http
            .post(URL_DELETE, null, {
              params: {
                id
              }
            })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.query()
                }
              })
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    getDictDataList,
    addOrUpdateHandle (row) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(row)
      })
    },
    clear () {
      // this.queryForm = createForm();
      // this.page.pageNo = 1;
      // 重置整个data
      Object.assign(this.$data, this.$options.data.bind(this)())
      // 重新加载数据
      this.initData()
      this.query()
    },
    // 分页, 每页条数
    pageSizeChangeHandle (val) {
      this.page.pageNo = 1
      this.page.pageSize = val
      this.query()
    },
    // 分页, 当前页
    pageCurrentChangeHandle (val) {
      this.page.pageNo = val
      this.query()
    },
    query () {
      console.log('query')

      this.dataListLoading = true
      this.$http
        .post('/cgjybzIndustry/getIndustryCount', this.selectedModule, {
          params: {
            ...this.queryForm,
            ...this.page
          }
        })
        .then(({ data: resp }) => {
          this.page.total = resp.data.total
          this.dataList = resp.data.list
        })
        .finally(() => {
          this.dataListLoading = false
        })
    },

    handleCurrentChange (data) {
      console.log('current-change ', data)
      if (data.isLeaf) {
        this.selectedModule = [data.id]
      } else {
        this.selectedModule = []
      }
      if (data.grade === 2) {
        this.queryForm.name = data.name
      }
      if (data.grade === 3) {
        this.queryForm.name = data.industryName
      }
      this.query()
    },
    handleCheckChange () {
      this.selectedModule = this.$refs.tree.getCheckedKeys(true)
      this.query()
    },
    hangyeChange (val) {
      var hyid = null
      for (var valKey in this.moduleTree) {
        var childley = this.moduleTree[valKey].children
        for (var childleyKey in childley) {
          if (childley[childleyKey].name == val) {
            hyid = childley[childleyKey].id
            this.$refs.tree.store._getAllNodes()[valKey].expanded = true

            break
          }
        }
      }
      this.$refs.tree.setCurrentKey(hyid)
      this.selectedModule = []
    },
    initData () {
      this.$http.get(URL_GET_ALL_MODULE).then(({ data: resp }) => {
        const { data } = resp
        const tree = data.reduce((ret, cur) => {
          if (ret.findIndex((d) => d.name === cur.division) < 0) {
            const children = data
              .filter((d) => {
                return d.division === cur.division
              })
              .reduce((ret1, cur1) => {
                if (
                  ret1.findIndex(
                    (dd) => dd.industryName === cur1.industryName
                  ) < 0
                ) {
                  ret1.push({
                    name: cur1.industryName,
                    ...cur1
                  })
                }
                return ret1
              }, [])

            children.forEach((c) => {
              const grandson = data
                .filter((d) => {
                  return c.industryName === d.industryName
                })
                .reduce((rm, rcur) => {
                  // if (
                  //   rm.findIndex((r) => r.industryType === rcur.industryType) <
                  //   0
                  // ) {
                  rm.push({
                    name: rcur.industryType + '-' + rcur.moduleName,
                    ...rcur,
                    isLeaf: true
                  })
                  // }
                  return rm
                }, [])
              c.children = grandson
            })

            ret.push({
              name: cur.division,
              ...cur,
              children
            })
          }
          return ret
        }, [])
        this.moduleTree = tree.filter((item) => item.name)
        this.moduleTree.map((m) => {
          const index = 1
          m.grade = index
          if ('children' in m) {
            this.addGrade(m.children, index)
          }
        })
        console.log('moduleTree', this.moduleTree)

        for (var i = 0; i < this.moduleTree.length; i++) {
          var keyobj1 = this.moduleTree[i]
          keyobj1.id = i + 1
          for (var n = 0; n < keyobj1.children.length; n++) {
            var keyobj2 = keyobj1.children[n]
            keyobj2.id = (keyobj1.id) * 10 + n + 1
            // for (var m = 0; m < keyobj2.children.length; m++) {
            //   var keyobj3 = keyobj2.children[m]
            //   keyobj3.id = (keyobj2.id) * 10 + m + 1
            // }
          }
        }
      })
    },
    addGrade (m, index) {
      m.map((ev) => {
        ev.grade = index + 1
        if ('children' in ev) {
          this.addGrade(ev.children, index + 1)
        }
      })
    }
  }
}
</script>

<style lang="scss">
.quota-tree {
  width: 100%;
  .el-tree {
    color: #212121;
  }
  .el-tree-node__content {
    height: 32px;
  }

  .el-tree-node .is-current > .el-tree-node__content {
    background: #3d76cc;
    /* background: none; */
    color: white;
  }
}
</style>
